package com.xinlin.generator.util;

import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Component
public class ResourceDirectoryScanner {
    private static final String CLASSPATH_PREFIX = "classpath*:";
    private final ResourcePatternResolver resolver;

    public ResourceDirectoryScanner() {
        this.resolver = new PathMatchingResourcePatternResolver();
    }

    public List<String> scanDirectory(String pathPattern,String vv)  {
        List<String> list = new ArrayList<>();
        try {
            Resource[] resources = resolver.getResources(CLASSPATH_PREFIX + pathPattern);
            for (Resource resource : resources) {
                if (resource.isReadable()) {
                    if(resource.getFilename().endsWith("vm")){
                        String path = getResourcePath(resource);
                        path = path.substring(path.indexOf(vv));
                        list.add(path);
                        System.out.println("Found resource: " + path);
                    }
//                    System.out.println("Found resource: " + getResourcePath(resource));
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        return list;
    }

    public List<String> scanDirectoryV1(String pathPattern,String vv)  {
        List<String> list = new ArrayList<>();
        try {
            Resource[] resources = resolver.getResources(CLASSPATH_PREFIX + pathPattern);
            for (Resource resource : resources) {
                if (resource.isReadable()) {
                    String path = getResourcePath(resource);
                    list.add(path.substring(path.indexOf(vv),path.length()));
                    System.out.println("Found resource: " + getResourcePath(resource));
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        return list;
    }

    private String getResourcePath(Resource resource) {
        try {
//            System.out.println(resource.getFile().g);
            return resource.getURL().toString()
                .replace("jar:file:", "")
                .replace("!/", "/");
        } catch (IOException e) {
            return resource.getFilename();
        }
    }
}
